package com.example.sunsg.okhttptest.Manager;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.net.Uri;
import android.text.TextUtils;

import com.example.sunsg.okhttptest.TheApplication;
import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.DraweeView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

/**
 * Created by sunsg on 15/12/9.
 * @description facebook 图片加载管理类
 */
public class FrescoManager {
    /**包名*/
    private static String packageName;
    /**本地图片 scheme header*/
    private static final String LOCAL_SCHEME = "file://";
    /**资源文件 scheme header*/
    private static final String RES_SCHEME = "res://";
    /**要加载的 图片路径 uri 包括网络路径 本地路径 资源文件的路径*/
    private Uri uri;
    /**默认图片资源id*/
    private int placeHolderResourceId;
    /**是否自动旋转图片*/
    private boolean autoRotate;
    /**图片的宽 （被修改后）*/
    private int resizeWidth;
    /**图片的高 （被修改后）*/
    private int resizeHeitht;
    /**是否自动播放gif图片*/
    private boolean autoPlayAnimations;
    /**进度条*/
    private Drawable progressBarDrawable;
    /**进度监听 图片加载成功 或 加载失败时的回调*/
    private ControllerListener controllerListener;

    public FrescoManager(Builder builder){
        this.uri = builder.uri;
        this.placeHolderResourceId = builder.placeHolderResourceId;
        this.autoRotate = builder.autoRotate;
        this.resizeWidth = builder.resizeWidth;
        this.resizeHeitht = builder.resizeHeitht;
        this.progressBarDrawable = builder.progressBarDrawable;
        this.autoPlayAnimations = builder.autoPlayAnimations;
        this.controllerListener = builder.controllerListener;
    }

    public static Builder loadUrl(String url){
        return loadUri(Uri.parse(url));
    }

    public static Builder loadFilePath(String filePath){
        filePath = getFilePath(filePath);
        return loadUri(Uri.parse(filePath));
    }

    public static Builder loadResourceId(int resourceId){
        String res = getResPath(resourceId);
        return loadUri(Uri.parse(res));
    }


    public static Builder loadUri(Uri uri){
        return new Builder(uri);
    }

    /**开始加载图片*/
    public void into(DraweeView draweeView){
        SimpleDraweeView simpleDraweeView = null;
        if(draweeView instanceof  SimpleDraweeView){
            simpleDraweeView = ((SimpleDraweeView) draweeView);
            if(uri != null){
                ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(uri);
                if(autoRotate){
                    imageRequestBuilder.setAutoRotateEnabled(autoRotate);
                }
                if(resizeWidth >0 && resizeHeitht >0){
                    imageRequestBuilder.setResizeOptions(new ResizeOptions(resizeWidth,resizeHeitht));
                }

                PipelineDraweeControllerBuilder controllerBuilder = Fresco.newDraweeControllerBuilder();

                controllerBuilder.setImageRequest(imageRequestBuilder.build());
                if(autoPlayAnimations){
                    controllerBuilder.setAutoPlayAnimations(autoPlayAnimations);
                }

                if(controllerListener != null){
                    controllerBuilder.setControllerListener(controllerListener);
                }

                GenericDraweeHierarchy hierarchy = simpleDraweeView.getHierarchy();
                if(placeHolderResourceId != 0){
                    hierarchy.setPlaceholderImage(placeHolderResourceId);
                }
                if(progressBarDrawable != null){
                    hierarchy.setProgressBarImage(progressBarDrawable);
                }

                simpleDraweeView.setHierarchy(hierarchy);
                simpleDraweeView.setController(controllerBuilder.build());
            }

        }
    }

    /**获取资源文件的路径*/
    public static String getResPath(int resId){
        StringBuilder builder = new StringBuilder();
        builder.append(RES_SCHEME).append(getPackageName()).append("/").append(resId);
        return builder.toString();
    }

    /**获取本地文件的路径*/
    public static String getFilePath(String filePath){
        StringBuilder builder = new StringBuilder();
        if(!filePath.startsWith(LOCAL_SCHEME)){
            filePath = new StringBuilder(LOCAL_SCHEME).append(filePath).toString();
        }
        builder.append(filePath);
        return builder.toString();
    }

    /**获取报名*/
    public static String getPackageName(){
        if(TextUtils.isEmpty(packageName)){
            packageName = TheApplication.getApplication().getPackageName();
        }
       return packageName;
    }

    /**获取bitmap
     * 返回的bitmap容易被回收 拿到bitmap时 建议根据此bitmap 创建一个新的bitmap
     * */
    public static void loadBitmap(Uri uri, BaseBitmapDataSubscriber listener){
        ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(uri).setProgressiveRenderingEnabled(true).build();
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest,TheApplication.getApplication());
        dataSource.subscribe(listener, CallerThreadExecutor.getInstance());
    }

    /**
     * DEMO
     *  FrescoManager.loadBitmap(Uri.parse(FrescoManager.getResPath(R.drawable.ren)),new BaseBitmapDataSubscriber(){
        @Override
        protected void onNewResultImpl(Bitmap bitmap) {

        }

        @Override
        protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

        }
        });
     */

    /**
     * 创建新的分享bitmap  有的手机经过handler处理之后 Fresco 加载的 bitmap 会被回收
     * @param oldBitmap
     * @return
     */
    public static Bitmap createNewBitmap(Bitmap oldBitmap){
        Bitmap bitmap = null;
        try {
            bitmap = Bitmap.createScaledBitmap(oldBitmap,oldBitmap.getWidth(),oldBitmap.getHeight(),true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    public static class Builder{
        private Uri uri;
        private int placeHolderResourceId;
        private boolean autoRotate;
        private int resizeWidth;
        private int resizeHeitht;
        private boolean autoPlayAnimations;
        private Drawable progressBarDrawable;
        private ControllerListener controllerListener;

        public  Builder(Uri uri){
            this.uri = uri;
        }

        public Builder placeImageHolder(int placeHolderResourceId){
            this.placeHolderResourceId = placeHolderResourceId;
            return this;
        }

        public Builder autoRotate(boolean autoRotate){
            this.autoRotate = autoRotate;
            return this;
        }

        public Builder resize(int width,int height){
            this.resizeWidth = width;
            this.resizeHeitht = height;
            return this;
        }

        public Builder autoPlayAnimations(boolean autoPlayAnimations){
            this.autoPlayAnimations = autoPlayAnimations;
            return this;
        }

        public Builder progressBarDrawable(Drawable progressBarDrawable){
            this.progressBarDrawable = progressBarDrawable;
            return this;
        }

        public Builder controllerListener(BaseControllerListener controllerListener){
            this.controllerListener = controllerListener;
            return this;
        }

        public FrescoManager builder(){
            return new FrescoManager(this);
        }


    }

}
